package VMM;
import Exceptions.PageOverflowEx;

/**
 * Models a page table by storing a list of page numbers and associated frame
 * numbers
 * 
 * @author allanwatson
 * @changelog 9/2/12 Tidied up code and comments allowed the class to return
 *            it's size 15/2/12 Included number counts in the print out.
 *            Correcting the counters. 16/2/12 New method to check a frame
 *            doesn't already belong to the TLB/page table 17/2/12 Corrected an
 *            array looping error. To invalidated pagenumbers set them to -1
 *            18/2/12 New exceptions. Code and comment clean.
 */

public class PageTable {
	private int[] pageTab;
	private int size;

	public PageTable(int entries) {
		size = entries;
		pageTab = new int[size];
		for (int n = 0; n < pageTab.length; n++)
			pageTab[n] = -1;// fill table with invalid values
	}

	/**
	 * Record a page to a frame number
	 */
	public void add(int pageNo, int frameNo) {
		// check frameNo doesn't already exist
		for (int x = 0; x < pageTab.length; x++)
			if (pageTab[x] == frameNo)
				pageTab[x] = -1;// if it does replace with invalid

		pageTab[pageNo] = frameNo;// set new pageNo
	}

	/**
	 * Returns a frame Number or -1 if no frame number exists/invalid
	 */
	public int getFrameNo(int pageNo) {
		int fNo = pageTab[pageNo];

		return fNo;
	}

	/**
	 * Return the value associated with specific page
	 */
	public boolean pageIsEmpty(int pageNo) throws PageOverflowEx {
		if (pageNo >= size)
			throw new PageOverflowEx();

		if (pageTab[pageNo] == -1)
			return true;// return true is empty/invalid
		else
			return false;// has a valid number
	}

	/**
	 * @return The size of the page table
	 */
	public int getSize() {
		return this.size;
	}

}
